<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class online_day extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'songshu:online_day {day?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '每天上线文章数量统计';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $ymd = $this->argument('day');
        if(empty($ymd)){
           $ymd = date('Ymd',strtotime("-1 day")); 
        }
        $stime = strtotime($ymd);
        $etime = strtotime( $ymd." 23:59:59" );
        #echo $stime;
        #echo "\n";
        #echo $etime;
        $group = DB::table('check_article_queue')->select(DB::raw("count(`id`) as c,cat_id"))->whereBetween('exec_time',[$stime,$etime])
        ->where('exec',1)
        ->where('type',0)->groupBy('cat_id')->get()->toArray();
        foreach($group as $item){
            if( DB::table('check_day_online')->where('ymd',$ymd)->where('cat_id',$item->cat_id)->where('type',0)->exists() ){
                DB::table('check_day_online')->where('ymd',$ymd)->where('cat_id',$item->cat_id)->where('type',0)->update([
                    'total'=>$item->c,
                ]);
            }else{
                DB::table('check_day_online')->insert([
                    'ymd'=>$ymd,
                    'cat_id'=>$item->cat_id,
                    'type'=>0,
                    'total'=>$item->c,
                    'add_time'=>time(),
                ]);
            }
        }

        $group = DB::table('check_article_queue')->select(DB::raw("count(`id`) as c,cat_id"))->whereBetween('exec_time',[$stime,$etime])
        ->where('exec',1)
        ->where('type',1)->groupBy('cat_id')->get()->toArray();
        foreach($group as $item){
            if( DB::table('check_day_online')->where('ymd',$ymd)->where('cat_id',$item->cat_id)->where('type',1)->exists() ){
                DB::table('check_day_online')->where('ymd',$ymd)->where('cat_id',$item->cat_id)->where('type',1)->update([
                    'total'=>$item->c,
                ]);
            }else{
                DB::table('check_day_online')->insert([
                    'ymd'=>$ymd,
                    'cat_id'=>$item->cat_id,
                    'type'=>1,
                    'total'=>$item->c,
                    'add_time'=>time(),
                ]);
            }
        }
    }
}
